/*
 * @Author: your name
 * @Date: 2021-06-28 17:39:36
 * @LastEditTime: 2021-07-01 16:48:33
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \iwonmo\mmap.h
 */
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "lock.h"
#include "other.h"

typedef struct header_t header_t;
struct header_t
{
    int segsize; /* size of entire segment */
    int avail;   /* bytes available (not necessarily contiguous) */
};

typedef struct block_t block_t;
struct block_t
{
    int size; /* size of this block */
    int next; /* offset in segment of next free block */
};
#define BLOCKAT(offset) ((block_t *)((char *)shmaddr + offset))
#define OFFSET(block) ((int)(((char *)block) - (char *)shmaddr))

#ifdef max
#undef max
#endif
#define max(a, b) ((a) > (b) ? (a) : (b))

enum
{
    POWER_OF_TWO_BLOCKSIZE = 0
}; /* force allocated blocks to 2^n? */

enum
{
    DEFAULT_NUMSEG = 1,
    DEFAULT_SEGSIZE = 30 * 1024 * 1024
};

typedef struct slot_t slot_t;
struct slot_t
{
    int key;               /* 插槽 KEY */
    int expire_time;       /* 插槽的过期时间（毫秒） */
    long long create_time; /* 创建插槽时间 */
    slot_t *next;          /* 下一个插槽 */
};

typedef struct cache_header_t cache_header_t;
struct cache_header_t
{
    int num_hits;         /* total successful hits in cache */
    int num_misses;       /* total unsuccessful hits in cache */
    slot_t *deleted_list; /* linked list of to-be-deleted slots */
};

#define T apc_cache_t *
typedef struct apc_cache_t apc_cache_t; /* opaque cache type */
struct apc_cache_t
{
    void *shmaddr;          /* process (local) address of shared cache */
    cache_header_t *header; /* cache header (stored in SHM) */
    slot_t **slots;         /* array of cache slots (stored in SHM) */
    int num_slots;          /* number of slots in cache */
    int gc_ttl;             /* maximum time on GC list for a slot */
    int lock;               /* global semaphore lock */
};
ulong mtime();
extern int apc_module_init();
extern apc_cache_t *apc_cache_create(int size_hint, int gc_ttl);
extern int apc_cache_insert(apc_cache_t *cache,
                            int key,
                            int value);
extern void apc_debug_slot_list(apc_cache_t *cache);
extern int apc_slot_expire_time(apc_cache_t *cache, int key);
extern char *apc_cache_make_str(const char *str);
extern void *apc_slot_find(apc_cache_t *cache, int key);
extern void apc_sma_cleanup();